import { Dispatch } from 'redux';
import { getFormSelects } from '@/api/dic'
import type { IDicState, IParam } from './index.d';
import type { IFormDicSelects, IBuildingDicData } from '@/api/index.d';

export const MUDULE_NAME: string = 'dic';

export const types = {
  BUDING_DATA: 'BUDING_DATA', // 建筑楼信息
}

export default (state: IDicState = {
  [types.BUDING_DATA]: []
}, action: any) => {
  switch (action.type) {
    case types.BUDING_DATA:
      return Object.assign({}, state, {
        token: action.data
      })
    default: return state;
  }
}

// 获取字典
export function getDic(key: string) {
  return async (dispatch: Dispatch, getState: any): Promise<IBuildingDicData[]> => {
    let keyMap: IParam = {
      [types.BUDING_DATA]: {
        entity: 'Building',
        propertyKey: 'buildType',
      }
    }

    const dicData: IDicState = getState().dic;
    // 字典数据
    let data: IBuildingDicData[] = dicData[key];

    // 如果缓存里有字典数据 直接返回
    if (data && data.length) {
      return Promise.resolve(data)
    }

    // 如果缓存里面没有字典数据则调用接口获取
    const formParam: IFormDicSelects = keyMap[key];

    try {
      const res = await getFormSelects(formParam);
      data = res.data;

      dispatch({
        type: key,
        data
      })
    } catch { }
    return Promise.resolve(data);
  }
}
